package com.itheima.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.exception.BizException;
import com.itheima.mapper.ArticleMapper;
import com.itheima.pojo.Article;
import com.itheima.pojo.User;
import com.itheima.service.ArticleService;
import com.itheima.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    ArticleMapper articleMapper;
    @Override
    public void addArticle(Article article) {

        User user = ThreadLocalUtil.get();
        article.setCreateUser(user.getId());
        article.setUpdateTime(LocalDateTime.now());
        // 新增
        if (article.getId() == null){
            article.setCreateTime(LocalDateTime.now());
            if (articleMapper.countByTitle(article.getTitle(),article.getCategoryId(),article.getCreateUser()) > 0){
                throw new BizException("文章标题重复");
            }
            articleMapper.insertAritcle(article);
            return;
        }
        // 更新
        if (articleMapper.countByTitleAndid(article.getTitle(),article.getCategoryId(),article.getCreateUser(),article.getId()) > 0){
            throw new BizException("文章标题重复");
        }
        articleMapper.updateArticleById(article);

    }

    @Override
    public void updateArticle(Article article) {

        User user = ThreadLocalUtil.get();
        article.setCreateUser(user.getId());
        article.setUpdateTime(LocalDateTime.now());
        if (articleMapper.countByTitleAndid(article.getTitle(),article.getCategoryId(),article.getCreateUser(),article.getId()) > 0){
            throw new BizException("文章标题重复");
        }
        articleMapper.updateArticleById(article);

    }

    @Override
    public Article getArticleById(int id) {

        return articleMapper.getArticleById(id);
    }

    @Override
    public void deleteArticle(int id) {
        articleMapper.deleteArticle(id);
    }

    @Override
    public PageInfo<Article> findPage(int pageNum, int pageSize, Integer categoryId, String state) {

        PageHelper.startPage(pageNum,pageSize);
        User user =ThreadLocalUtil.get();
        List<Article> lists = articleMapper.findPage(categoryId,state,user.getId());

        return PageInfo.of(lists);
    }
}
